#include "Haffman.h"

using namespace std;

bandzip::bandzip(QWidget *parent)
  : QMainWindow(parent)
  , ui(new Ui::zip1)
{
  ui->setupUi(this);
  resize(910, 530);
  this->setWindowTitle("Bandzip1.0");

  // ui->pushButton->setFlat(true);
  connect(ui->actionnew,   &QAction::triggered, ui->pushButton, &QPushButton::clicked);
  connect(ui->actionclose, &QAction::triggered, this,           &QWidget::close);
  connect(ui->actionsize,  &QAction::triggered, [ = ]()
  {
    QMessageBox::information(this, "info", "压缩大小限制在10m以内");
  }
          );
  connect(ui->actionhow, &QAction::triggered, [ = ]()
  {
    QMessageBox::information(this, "info", "每次解压时把解压文件和.code在同一目录下");
  }
          );
}

bandzip::~bandzip()
{
  delete ui;
}

void bandzip::on_pushButton_clicked()
{
  QString path = QFileDialog::getOpenFileName(this, "打开文件", "C:\\Users\\11861\\Desktop");
  if (path != nullptr)
  { qDebug() << path;
    a.read(path);
    a.count();
    a.make_haffman();
    a.zip();
    a.write(path);
    a.savecode();

    // qDebug()<<a.origin_size<<a.final_size;
    double  ans = (a.final_size / a.origin_size) * 100;
    QString s   = QString::number(ans);
    QMessageBox::information(this, "cue", "压缩后和压缩前之比" + s + "%"); }
}

void haffman::new_sort(tree *a[], int b, int e) // 快排原理
{
  if (b >= e) return;
  tree *tem;
  int   k = a[b]->times, left = b, right = e;
  while (left < right)
  {
    while (left < right && a[right]->times >= k) right--;
    tem = a[left]; a[left] = a[right]; a[right] = tem;
    while (left < right && a[left]->times < k) left++;
    tem = a[left]; a[left] = a[right]; a[right] = tem;
  }
  a[right] = a[left];
  new_sort(a, b,         right - 1);
  new_sort(a, right + 1, e);
}

void haffman::wbit(int i)
{
  buffer[max_bu] = buffer[max_bu] | (i << bu);
  ++bu;
  if (bu >= 8)
  {
    bu = 0;
    ++max_bu; // bit+1
  }
}

void bandzip::on_pushButton_2_clicked()
{
  QString path = QFileDialog::getOpenFileName(this, "打开文件");
  if (path != nullptr)
  {
    a.ReadZipFile(path);
    a.readcode();
    a.unzip(path);
  }
}
